package com.gopay.cron.event.handler;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.gopay.common.datasource.DBType;
import com.gopay.common.datasource.DbContextHolder;
import com.gopay.common.domain.report.Event;
import com.gopay.common.event.EventState;
import com.gopay.common.event.handler.EventHandler;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.report.dao.MqEventInfoDAO;
import com.gopay.common.report.dao.ReportConsoleBalanceQueryDAO;

@Service(value="frozeAmountDefaultHandler")
public class FrozeAmountDefaultHandler implements EventHandler {

    @Resource(name = "reportConsoleBalanceQueryDAO")
    private ReportConsoleBalanceQueryDAO reportConsoleBalanceQueryDAO;
    
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
    
    @Resource(name = "mqEventInfoDAO")
    private MqEventInfoDAO mqEventInfoDAO;
    
    @Transactional(value="reportTransactionManager")
    public void handler(Event e) throws Exception {
        DbContextHolder.setDbType(DBType.DS_ONLY_READ.value);
        Map<String, Object> map = StringUtils.isNotBlank(e.getSnapshot())? (Map<String, Object>) JSONObject.parse(e.getSnapshot()):new HashMap<String, Object>();
        //String acctId = (String) map.get("acctId");
        String sql = "select a.acct_id,a.frez_amt from ACPS_ACCT_MAST a where a.acct_id=:acctId";
        List<Object[]> result =commonQueryDAO.findBySql(sql, map) ;
        if(null == result || result.size() < 1){
            return;
        }
        Object[] o = result.get(0);
        Object _freAmt = o[1];
        BigDecimal frezAmt = new BigDecimal(null == _freAmt ? "0":_freAmt.toString());
        map.put("frezAmt", frezAmt);
        this.updateReportConsoleBalanceQueryAndEvent(map, e);
        
        
    }
    
    
    public void updateReportConsoleBalanceQueryAndEvent(Map<String, Object> param, Event e){
        DbContextHolder.setDbType(DBType.DS_REPORT.value);
        String updateHql = "update ReportConsoleBalanceQuery r set r.frezAmt=:frezAmt where r.acctId=:acctId";
        reportConsoleBalanceQueryDAO.updateByHql(updateHql, param);
        Event result = mqEventInfoDAO.find(Event.class, e.getId());
        if(null!=result){
            result.setLastUpdTs(new Date());
            result.setStat(EventState.SUCCESS.value);
            mqEventInfoDAO.update(result);
        }
        
    }

}
